﻿#include "stdafx.h"
#include "FuncSaveUnicodeFile.h"
#include<iostream>
#include<fstream>
#include<istream>
#include<string>

FuncSaveUnicodeFile::FuncSaveUnicodeFile()
{
}

FuncSaveUnicodeFile::~FuncSaveUnicodeFile()
{
}

void FuncSaveUnicodeFile::saveWideFile(ostream& out, wchar_t const* str, int size)
{
	char const* pos = (char const*)str;
	if (str[0] != 0xFEFF) // 写入unicode文件头
	{
		char const* const utf16head = _T("\xFF\xFE ");
		out.write(utf16head, 2);
	}

	out.write(pos, size);
}

int FuncSaveUnicodeFile::main()
{
	//预先保存一个a.txt，其内容为：
	/*
	    abcdefg
	    何何何글금기
	*/
	wchar_t wc[50] = { 0 };                          // 读取的内容用宽字符保存(其实也可以使用short，更有利于跨平台)
	fstream wfile(_T("D:\YJK_WORK\mep\YJKCAD\add_layer.cpp"), ios::binary | ios::in);
	wfile.read((char*)wc, sizeof(wc));
	ofstream out("add_layer_new.cpp ", ios::binary | ios::out);  // 把a.txt的内容读取，并保存为b.txt
	saveWideFile(out, wc, sizeof(wc));
	out.close();
	return 0;
}

void FuncSaveUnicodeFile::saveTTTT()
{
	CStdioFile file;
	if (!file.Open(_T("D:\\YJK_WORK\\mep\\YJKCAD\\add_layer.cpp"), CFile::modeReadWrite))
	{
		file.Open(_T("D:\\YJK_WORK\\mep\\YJKCAD\\add_layer.cpp"), CFile::modeCreate | CFile::modeReadWrite);
	}

	wchar_t wstr[300];

	CTime time = CTime::GetCurrentTime();
	//wstr.Format(_T("%d-%-d-%-d %d:%-d:%-d 记录："), time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(), time.GetMinute(), time.GetSecond());
	//str字符串以\0结尾，也就是说最后还有一个字节没显示出来但却存在，str.getlenth()不算最后那个\0;

	WORD num = WideCharToMultiByte(CP_ACP, NULL, wstr, -1, NULL, 0, NULL, FALSE);
	char *p = new char[num];
	memset(p, 0, num);
	WideCharToMultiByte(CP_ACP, NULL, wstr, -1, p, num, NULL, FALSE);
	file.Write(p, strlen(p));
	file.SeekToEnd();
	file.Write("\n", 1);//一个换行符\n，写的时候用的asci码，换行用一个字节；但是读的时候，file.getlenth()将换行解释成两个字节；
	file.SeekToEnd();
	file.Write("好", strlen("好"));
	file.Close();
}
